package n15_设计模式_交替运行输出;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.LockSupport;

/**
 * @author fu
 * @date 2022-01-12 22:08
 * 概要：
 * ---------------------------------------------------------------
 * |                                                              |
 * |   [线程1] 输出a 5次； [线程2] 输出b 5次； [线程3] 输出c 5次； 现在要求输出 abcabcabcabcabc    |
 * |                                                             |
 * |=============================================================
 */
public class T3_alternate_by_parkunpark {

    static Thread t1;
    static Thread t2;
    static Thread t3;

    public static void main(String[] args) {
        final ParkUnpark pu = new ParkUnpark(5);

        t1 = new Thread(()->{
            pu.print("a", t2);
        }, "t1");
        t2 = new Thread(()->{
            pu.print("b", t3);
        }, "t2");
        t3 = new Thread(()->{
            pu.print("c", t1);
        }, "t3");

        // 1. 三个线程进入 park
        t1.start();
        t2.start();
        t3.start();

        // 2. 将t1线程 唤醒(下一轮将继续park) ；  此时 next=t2 将被unpark 唤醒
        //    t2 将在park()醒来 进行打印；       此时 next=t3 将被唤醒
        LockSupport.unpark(t1);

    }

}

@Slf4j(topic = "c.ParkUnpark")
class ParkUnpark {

    public void print(String str, Thread next){
        for (int i = 0; i < loopNumber; i++) {
            LockSupport.park();
            log.debug(str);

            LockSupport.unpark(next);
        }
    }

    private int loopNumber;

    public ParkUnpark(int loopNumber) {
        this.loopNumber = loopNumber;
    }
}
